package nccloud.web.hrppl.pjapplication.pjappl.action;


import java.util.Collections;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;
import nc.itf.hrppl.pjapplication.IUapbdFourCGProjectService;
import nc.itf.hrppl.pjapplication.pjappl.IPJApplHVOService;
import nc.itf.uif.pub.IUifService;
import nc.mddb.baseutil.MDDAOUtil;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.ct.uitl.ArrayUtil;
import nc.vo.hrppl.pjapplication.AggPjapplVO;
import nc.vo.hrppl.pjapplication.PJApplHVO;
import nc.vo.hrppl.pjapplication.PjapplPVO;
import nc.vo.pub.ISuperVO;
import nc.vo.pub.lang.UFDouble;
import ncc.bs.query.service.IQueryTranslateService;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.ui.model.GridModel;
import nccloud.framework.web.ui.model.row.Cell;
import nccloud.framework.web.ui.model.row.Row;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCard;
import nccloud.framework.web.ui.pattern.grid.Grid;
import nccloud.web.codeplatform.framework.action.base.BaseAction;
import nccloud.web.codeplatform.framework.action.base.RequestDTO;
import nccloud.web.codeplatform.framework.action.base.RequstParamWapper;
import nccloud.web.codeplatform.framework.action.base.ResultWapper;
import nccloud.web.codeplatform.framework.action.base.VOTransform;

/**
 * 保存action（主子、单表、单form）
 */
public class SavePJApplHVOAction extends BaseAction{

	@Override
	public Object doAction(IRequest request, RequstParamWapper paramWapper) throws Throwable{
		RequestDTO param = VOTransform.toVO(paramWapper.requestString,RequestDTO.class);
		
		IPJApplHVOService service = ServiceLocator.find(IPJApplHVOService.class);

		AggPjapplVO[] vos = this.getVOs(param, AggPjapplVO.class);
		vos = service.saveAggPjapplVO(vos[0]);


		if(vos[0].getParentVO().getDef3()!=null) {
			String condition =" officedept='"+vos[0].getParentVO().getOfficedept()+"'"
					+ " and belongpro='"+vos[0].getParentVO().getBelongpro()+"'"
					+ " and pk_pjappl !='"+vos[0].getParentVO().getPk_pjappl()+"'"
					+ " and approvestatus ='-1'"
					+ " and def3 !='~'";
			AggPjapplVO[] aggvos = service.listAggPjapplVOByCondition(condition);

			if(aggvos.length>0) {
				Arrays.sort(aggvos, (o1, o2) -> {
					String def31 = Objects.toString(o1.getParentVO() != null ? o1.getParentVO().getDef3() : "", "");
					String def32 = Objects.toString(o2.getParentVO() != null ? o2.getParentVO().getDef3() : "", "");

					// 将字符串转换为整数进行比较
					int num1 = Integer.parseInt(def31);
					int num2 = Integer.parseInt(def32);

					// 处理可能的NumberFormatException（如果def3不是有效的数字字符串）
					try {
						return Integer.compare(num1, num2);
					} catch (NumberFormatException e) {
						// 如果发生异常，可以根据需要处理，比如将非数字字符串视为最小值或最大值
						// 这里简单地将非数字字符串视为最大值（返回1表示o1排在o2后面）
						return def31.compareTo(def32); // 这实际上不会触发，因为我们已经转换为int了，但保留以防万一
					}
				});

				//遍历结果
				// 获取所有不为空的结果
//        List<String> nonEmptyDef3s = Arrays.stream(aggvos)
//                .map(AggPjapplVO::getDef3)
//                .filter(Objects::nonNull) // 过滤掉null值
//                .filter(s -> !s.isEmpty()) // 过滤掉空字符串（根据需要调整）
//                .collect(Collectors.toList());
				List<Integer> nonEmptyDef3s =new ArrayList();
				for(AggPjapplVO vo:aggvos) {
					if(vo.getParentVO().getDef3()!=null&&!vo.getParentVO().getDef3().isEmpty()) {
						nonEmptyDef3s.add(Integer.parseInt(vo.getParentVO().getDef3()));

					}
				}
				if(nonEmptyDef3s.size()>0) {
					Collections.sort(nonEmptyDef3s);
				}
				// 判断结果中是否含有新的排序值
				int def3 = Integer.parseInt(vos[0].getParentVO().getDef3());
				//boolean ss = nonEmptyDef3s.contains(def3);
				if(nonEmptyDef3s.contains(def3)) {
					for(AggPjapplVO vo:aggvos) {
						//已经根据def3从大到小排序
						//当前值+1在nonEmptyDef3s内没有 则表示不用再继续修改
						//当前值
						int newdef3 = -1;
						if(vo.getParentVO().getDef3()!=null&&!vo.getParentVO().getDef3().isEmpty()) {
							newdef3 = 	Integer.parseInt(vo.getParentVO().getDef3());
						}
						if(newdef3>=def3) {
							vo.getParentVO().setDef3(newdef3+1+"");
							service.saveAggPjapplVO(vo);
							if(!nonEmptyDef3s.contains(newdef3+1)) {
								break;
							}
							//	nonEmptyDef3s.add(newdef3+1);

						}

					}
				}
			}

		}
		ResultWapper o = (ResultWapper) buildResult(param,true,null,vos);
		ExtBillCard data = (ExtBillCard) o.getData();
	    //start modify by wy at 2024年7月26日
		data = TranslateActionUtil.translateAggvoVO(data,"pjapplpSub");
		Row row = data.getHead().getModel().getRows()[0];
		Cell expertgroupmember = row.getValues().get("expertgroupmember");
		if (expertgroupmember != null && expertgroupmember.getValue() != null){
			String value = expertgroupmember.getValue().toString();
			if (value.contains(",")){
				IUifService uifService = ServiceLocator.find(IUifService.class);
				DefdocVO[] defdocVOS = (DefdocVO[]) uifService.queryByCondition(DefdocVO.class, " pk_defdoc in " + MDDAOUtil.getInSql(value.split(",")));
				if (defdocVOS != null && defdocVOS.length >0){
					StringBuffer sb = new StringBuffer();
					for (DefdocVO defdocVO : defdocVOS) {
						sb.append(defdocVO.getName()).append(",");
					}
					expertgroupmember.setDisplay(sb.deleteCharAt(sb.length() - 1).toString());
				}
			}
		}

		return o;
	
	}
	
	// start modify by wy at 2024年7月25日
	/**
	  *  翻译资本项目采购页签中的参照字段
	 * @param data
	 * @return
	 * @throws Throwable
	 */
	@SuppressWarnings("rawtypes")
	protected ExtBillCard translateProjectCG(ExtBillCard data) throws Throwable{
		Grid grid = data.getBody("pjapplpSub");
		if(grid == null) return data;
		IQueryTranslateService service = ServiceLocator.find(IQueryTranslateService.class);
		GridModel gridModel = grid.getModel();
		Row[] lrows = gridModel.getRows();
		if(lrows != null) {
			for(Row row : lrows) {
				Map<String, Cell> values = row.getValues();
				if(values != null) {
					Cell celtype = values.get("vbdef1");
					if(celtype != null) {
						celtype.setDisplay(service.getFourCGProject(celtype.getValue()));
					}
				}
			}
		}
		return data;
	}
	// end modify by wy 
}